<?php
/**
 * Created by PhpStorm.
 * User: shi_wenhu@qq.com
 * Date: 2018/6/15
 * Time: 11:47
 */

class PostManJsonTool
{
    public static function jsonToFormData()
    {
        $applicationJsonArr = [];
        $applicationJson    = file_get_contents("php://input");
        if ($_SERVER['CONTENT_TYPE'] == 'application/json' && !empty($applicationJson)) {
            $applicationJsonArr = json_decode($applicationJson, true);
        } else {
            if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                $applicationJsonArr = $_POST;
            } else {
                $applicationJsonArr = $_GET;
            }
        }
        $attr = self::runAttr($applicationJsonArr, '');
        $formate = [];
        $getData = [];
        foreach ($attr as $k => $v) {
            $keyArr = explode('/', $k);
            $t      = '';
            foreach ($keyArr as $k2 => $v2) {
                if (count($keyArr) > 1) {
                    if ($k2 == 0) {
                        $t = $t . '' . $v2 . '';
                    } else {
                        $t = $t . '[' . $v2 . ']';
                    }
                } else {
                    $t = $v2;
                }
            }
            $formate[] = $t . ':' . $v . '';
            $getData[$t] =$v;
        }

        echo "GET格式：\n \n";
        echo http_build_query($getData) . "\n";

        echo "\n \n \nPOST格式:\n \n";

        foreach ($formate as $k => $v) {
            echo $v . "\n";
        }

    }

    /**
     * 无限极路径转换
     * @param $attr
     * @param string $strPrevKey
     * @return array
     */
    protected static function runAttr($attr, $strPrevKey = '')
    {
        static $temp = [];

        foreach ($attr as $k => $v) {
            $strNowKey = $strPrevKey ? $strPrevKey . '/' . $k : $k;
            if (is_array($v)) {
                self::runAttr($v, $strNowKey);
            } else {
                $temp[$strNowKey] = $v;
            }
        }
        return $temp;
    }

}

PostManJsonTool::jsonToFormData();
